package com.liefox.serviceorder.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liefox.commonutils.JwtUtils;
import com.liefox.commonutils.R;
import com.liefox.serviceorder.entity.Order;
import com.liefox.serviceorder.service.OrderService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author liefox
 * @since 2021-07-22
 */
@RestController
@RequestMapping("/serviceorder/order")
//@CrossOrigin
public class OrderController {


    @Autowired
    private OrderService orderService;


    @ApiOperation(value = "生成订单方法")
    @PostMapping("createOrder/{courseId}")
    public R save(@PathVariable String courseId, HttpServletRequest request) {
        if (!StringUtils.isEmpty(JwtUtils.getMemberIdByJwtToken(request))) {
            String orderId = orderService.saveOrder(courseId, JwtUtils.getMemberIdByJwtToken(request));
            return R.ok().data("orderId", orderId);
        } else {
            return R.error().code(20005).message("未登录！");
        }

    }

    @ApiOperation(value = "根据订单id查询")
    @GetMapping("getOrder/{orderId}")
    public R get(@PathVariable String orderId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no", orderId);
        Order order = orderService.getOne(wrapper);
        return R.ok().data("item", order);
    }


    @ApiOperation(value = "根据课程id查询用户是否购买")
    @GetMapping("isBuyCourse/{courseId}/{memberId}")
    public Boolean isBuyCourse(@PathVariable String courseId, @PathVariable String memberId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", courseId);
        wrapper.eq("member_id", memberId);
        wrapper.eq("status", 1);
        final int i = orderService.count(wrapper);
        if (i > 0) {
            return true;
        } else {
            return false;
        }

    }

}

